package com.cykj.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtils {
    private static SqlSessionUtils sqlSessionUtils;
    private SqlSessionUtils(){

    }
    public synchronized static SqlSessionUtils getInstance(){
        if (sqlSessionUtils == null){
            sqlSessionUtils = new SqlSessionUtils();
        }
        return sqlSessionUtils;
    }
    public Object getSqlSession(Class<?> c){
        //1.获取配置文件
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //2.创建sqlSession工厂建造器，获取数据库链接用的
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //3.通过工厂建造器来创建接口工厂
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
        //4.获取数据库链接sqlSession（自动提交）
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        Object mapper = sqlSession.getMapper(c);
        return mapper;
    }
}
